package cn.edu.zjut.mina.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.zjut.mina.bean.RoomInfo;
import cn.edu.zjut.mina.bean.RoomInfo_XCMJ;
import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.bean.UserSession;
import cn.edu.zjut.mina.interf.IRoomInfo;
import cn.edu.zjut.mina.po.TotalGameResult;
import cn.edu.zjut.mina.po.UserInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalReq;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.repository.UserInfoRepository;
import cn.edu.zjut.mina.service.IUserCreateRoomService;
import cn.edu.zjut.mina.util.DateUtils;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.RoomIdInfo;
import cn.edu.zjut.mina.util.UserMap;
import cn.edu.zjut.mina.util.UserSessionMap;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
/**
 * 创建房间 (不可重复创建)
 * @author 张宇翔
 *
 */

@Service("userCreateRoomService")
public class UserCreateRoomServiceImpl implements IUserCreateRoomService{
	/**
	 * 用于存放用户信息的集合
	 */
	private final UserSessionMap userSessionMap = UserSessionMap.getInstance();
	
	
	/**
	 * 用于存放用户信息的集合
	 */
	private final UserMap userMap = UserMap.getInstance();
	
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	
	
	
	@Transactional(rollbackFor=Exception.class)
	
	public JMessageProtocalRes createRoom(StandardFormat inJson,IoSession session){
		int gameType=inJson.gameType;
		switch(gameType){
		case 0:
			return createRoom_xcnn(inJson,session);
		case 1:
			return createRoom_xcmj(inJson,session);
			default:
				return createRoom_xcnn(inJson,session);
		}
	}
	
	
	public JMessageProtocalRes createRoom_xcnn(StandardFormat inJson, IoSession session) {
		// TODO Auto-generated method stub
		System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "创建房间");
		
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		
		// 以下代码，防止多次创建。 此处userMap一定存在对应userId的user。所以if可删
		if (userMap.get(inJson.userId) != null) {
			UserInfo mRoomOwner = userMap.get(inJson.userId).user;
			String roomId = mRoomOwner.getRoomId();
			if (roomId != null && userSessionMap.get(roomId) != null) {//已经创建过房间
				outJson.userId = inJson.userId;
				outJson.result = false;
				outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_HAVECREATEDINFO;
				res.setResultCode(ProtocalRegulation.CREATEROOM);
				datas = GsonUtils.beanToJson(outJson).trim();
				res.setContent(datas);
				return res;
			}
		}
		
		//没有创建过房间的可以创建房间 
		//获取房间号
		String roomId = RoomIdInfo.getRoomId();
		if (roomId == null) {
			outJson.userId = inJson.userId;
			outJson.result = false;
			outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_ROOMIDNULLINFO;
    	} else if (roomId.equals("")) {//房间爆满
			outJson.userId = inJson.userId;
			outJson.result = false;
			outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_ROOMFULLINFO;
    	} else {
    		/**
			 * 以房间号为单位保存用户session
			 */
			if (userSessionMap.get(roomId) == null) {
				System.out.println("here");
				UserInfo mRoomOwner = userMap.get(inJson.userId).user;
				if (mRoomOwner == null) 
					mRoomOwner = userInfoRepository.findByUserId(inJson.userId);
				mRoomOwner.setCredits(0);
				mRoomOwner.setPosition(0);//房主的位置是0
				mRoomOwner.setRoomId(roomId);//玩家所在的房间号
				System.out.println("roomId = " + roomId);
				
				/**
				 * 初始化房间数据
				 */
				IRoomInfo mRoomInfo = new RoomInfo();
				mRoomInfo.setGameType(0);
				mRoomInfo.setRoomId(roomId);//设置房间号
				mRoomInfo.setRatio(inJson.ratio);//设置初始倍率
				mRoomInfo.setParticipation(inJson.participation);//参与人数
				mRoomInfo.setNumber_of_games(inJson.number_of_games);//实际游戏局数
				mRoomInfo.setActual_number_of_games(0);//当前游戏局数
				mRoomInfo.setLzxs(inJson.lzxs);//轮庄形式
				mRoomInfo.setCreateRoomPlayerId(inJson.userId);//设置开房用户Id
				mRoomInfo.setCriticalOfTwoTimes(inJson.criticalOfTwoTimes);//2倍的临界值(也就是包不包含7)
				mRoomInfo.setActualParticipation(1);//当前人数
				mRoomInfo.setDeductRoomCard(inJson.deductRoomCard);//需要扣除的房卡数
				
				//本局游戏的基础信息设置
				TotalGameResult totalGameResult = new TotalGameResult();
				totalGameResult.setParticipation(inJson.participation);//设置参与人数
				totalGameResult.setBeginTime(new Date());//开房时间
				totalGameResult.setRoomId(roomId);//设置房间号
				totalGameResult.setNumber_of_games(inJson.number_of_games);//设置游戏局数
				totalGameResult.setActual_number_of_games(0);//当前游戏局数
				totalGameResult.setCreateRoomPlayerId(inJson.userId);//开房玩家Id
				totalGameResult.setCriticalOfTwoTimes(inJson.criticalOfTwoTimes);//两倍临界值
				totalGameResult.setLzxs(inJson.lzxs);//轮庄形式
				totalGameResult.setRatio(inJson.ratio);//设置初始倍率
				totalGameResult.setDeductRoomCard(inJson.deductRoomCard);//需要扣除的房卡数
				totalGameResult.setConstraintQuitRoom(0);//初始值是0
				
				mRoomInfo.setTotalGameResult(totalGameResult);
				
				UserSession mUserSession = new UserSession(mRoomOwner, session);
				List<UserSession> mListUserSession = new ArrayList<UserSession>();
				mListUserSession.add(mUserSession);
				mRoomInfo.setUserSessions(mListUserSession);
				userSessionMap.put(roomId, mRoomInfo);
			}
			outJson.userId = inJson.userId;
			outJson.result = true;
			outJson.roomId = roomId;
			outJson.gameType = 0;
			outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_SUCCESSINFO;
    	}
		res.setResultCode(ProtocalRegulation.CREATEROOM);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		
		return res;
	}

	
	

	public JMessageProtocalRes createRoom_xcmj(StandardFormat inJson, IoSession session) {
		// TODO Auto-generated method stub
		System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "创建房间");
		
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		
		// 以下代码，防止多次创建。 此处userMap一定存在对应userId的user。所以if可删
		if (userMap.get(inJson.userId) != null) {
			UserInfo mRoomOwner = userMap.get(inJson.userId).user;
			String roomId = mRoomOwner.getRoomId();
			if (roomId != null && userSessionMap.get(roomId) != null) {//已经创建过房间
				userSessionMap.remove(roomId);
				
//				outJson.userId = inJson.userId;
//				outJson.result = false;
//				outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_HAVECREATEDINFO;
//				res.setResultCode(ProtocalRegulation.CREATEROOM);
//				datas = GsonUtils.beanToJson(outJson).trim();
//				res.setContent(datas);
//				return res;
			}
		}
		
		//没有创建过房间的可以创建房间 
		//获取房间号
		String roomId = RoomIdInfo.getRoomId();
		if (roomId == null) {
			outJson.userId = inJson.userId;
			outJson.result = false;
			outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_ROOMIDNULLINFO;
    	} else if (roomId.equals("")) {//房间爆满
			outJson.userId = inJson.userId;
			outJson.result = false;
			outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_ROOMFULLINFO;
    	} else {
    		/**
			 * 以房间号为单位保存用户session
			 */
			if (userSessionMap.get(roomId) == null) {
				System.out.println("here");
				UserInfo mRoomOwner = userMap.get(inJson.userId).user;
				if (mRoomOwner == null) 
					mRoomOwner = userInfoRepository.findByUserId(inJson.userId);
				mRoomOwner.setCredits(0);
				mRoomOwner.setPosition(0);//房主的位置是0
				mRoomOwner.setRoomId(roomId);//玩家所在的房间号
				System.out.println("roomId = " + roomId);
				
				/**
				 * 初始化房间数据
				 */
				IRoomInfo mRoomInfo = new RoomInfo_XCMJ();
				mRoomInfo.setGameType(1);
				mRoomInfo.setRoomId(roomId);//设置房间号
				mRoomInfo.setParticipation(4);//参与人数
				mRoomInfo.setNumber_of_games(inJson.number_of_games);//游戏局数
				mRoomInfo.setActual_number_of_games(0);//当前游戏局数
				mRoomInfo.setCreateRoomPlayerId(inJson.userId);//设置开房用户Id
				mRoomInfo.setActualParticipation(1);//当前人数
				mRoomInfo.setDeductRoomCard(inJson.deductRoomCard);//需要扣除的房卡数
				
				//本局游戏的基础信息设置
			/*	TotalGameResult totalGameResult = new TotalGameResult();
				totalGameResult.setParticipation(inJson.participation);//设置参与人数
				totalGameResult.setBeginTime(new Date());//开房时间
				totalGameResult.setRoomId(roomId);//设置房间号
				totalGameResult.setNumber_of_games(inJson.number_of_games);//设置游戏局数
				totalGameResult.setActual_number_of_games(0);//当前游戏局数
				totalGameResult.setCreateRoomPlayerId(inJson.userId);//开房玩家Id
				totalGameResult.setCriticalOfTwoTimes(inJson.criticalOfTwoTimes);//两倍临界值
				totalGameResult.setLzxs(inJson.lzxs);//轮庄形式
				totalGameResult.setRatio(inJson.ratio);//设置初始倍率
				totalGameResult.setDeductRoomCard(inJson.deductRoomCard);//需要扣除的房卡数
				totalGameResult.setConstraintQuitRoom(0);//初始值是0
				
				mRoomInfo.setTotalGameResult(totalGameResult);
			*/	
				UserSession mUserSession = new UserSession(mRoomOwner, session);
				List<UserSession> mListUserSession = new ArrayList<UserSession>();
				mListUserSession.add(mUserSession);
				mRoomInfo.setUserSessions(mListUserSession);
				userSessionMap.put(roomId, mRoomInfo);
			}
			outJson.userId = inJson.userId;
			outJson.result = true;
			outJson.roomId = roomId;
			outJson.gameType = 1;
			outJson.resultInfo = ResultInfoConstUtils.CREATEROOM_SUCCESSINFO;
    	}
		res.setResultCode(ProtocalRegulation.CREATEROOM);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		
		return res;
	}
	
}

	



